package com.agileboot.attendance.domain.supplier.db;

import com.agileboot.attendance.domain.supplier.dto.SearchSupplierDTO;
import com.agileboot.common.core.page.PageQuery;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 供应商信息表 服务实现类
 * </p>
 *
 * @author agileboot
 * @since 2023-03-14
 */
@Service
@RequiredArgsConstructor
public class AttSupplierService extends ServiceImpl<AttSupplierMapper, AttSupplierEntity> {

    /**
     * 分页查询供应商列表
     *
     * @param query 查询参数
     * @return 分页结果
     */
    public Page<AttSupplierEntity> getSupplierList(PageQuery<SearchSupplierDTO> query) {
        Page<AttSupplierEntity> page = query.buildPage();
        SearchSupplierDTO param = query.getParam();

        LambdaQueryWrapper<AttSupplierEntity> wrapper = new LambdaQueryWrapper<>();
        
        // 动态添加查询条件
        if (StringUtils.isNotBlank(param.getSupplierName())) {
            wrapper.like(AttSupplierEntity::getSupplierName, param.getSupplierName());
        }
        if (StringUtils.isNotBlank(param.getSupplierCode())) {
            wrapper.like(AttSupplierEntity::getSupplierCode, param.getSupplierCode());
        }
        if (StringUtils.isNotBlank(param.getContactName())) {
            wrapper.like(AttSupplierEntity::getContactName, param.getContactName());
        }
        if (StringUtils.isNotBlank(param.getStatus())) {
            wrapper.eq(AttSupplierEntity::getStatus, param.getStatus());
        }
        
        // 添加基础条件
        wrapper.eq(AttSupplierEntity::getDeleted, 0)
               .orderByDesc(AttSupplierEntity::getCreateTime);

        return page(page, wrapper);
    }

    /**
     * 检查供应商编码是否重复
     *
     * @param supplierCode 供应商编码
     * @param supplierId 供应商ID（更新时使用）
     * @return 是否重复
     */
    public boolean isSupplierCodeDuplicated(String supplierCode, Long supplierId) {
        return lambdaQuery()
            .eq(AttSupplierEntity::getSupplierCode, supplierCode)
            .ne(supplierId != null, AttSupplierEntity::getSupplierId, supplierId)
            .exists();
    }

    /**
     * 检查供应商名称是否重复
     *
     * @param supplierName 供应商名称
     * @param supplierId 供应商ID（更新时使用）
     * @return 是否重复
     */
    public boolean isSupplierNameDuplicated(String supplierName, Long supplierId) {
        return lambdaQuery()
            .eq(AttSupplierEntity::getSupplierName, supplierName)
            .ne(supplierId != null, AttSupplierEntity::getSupplierId, supplierId)
            .exists();
    }
} 